package org.example.book.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import org.example.book.common.result.Result;
import org.example.book.dto.UserDTO;
import org.example.book.entity.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class UserController {

    @Autowired
    AuthenticationManager authManager;

    @Value("${jwt.secret:defaultSecretKey12345678901234567890}")
    private String Key;

    @PostMapping("/auth/login")
    public Result<Map<String, Object>> login(@RequestBody UserDTO user) {
        System.out.println("登录请求: " + user);

        // 1. 使用 AuthenticationManager 进行认证
        UsernamePasswordAuthenticationToken authRequest =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        try {
            Authentication authentication = authManager.authenticate(authRequest);

            // 2. 获取 UserDetails
            Object principal = authentication.getPrincipal();

            if (principal instanceof MyUserDetails) {
                MyUserDetails userDetails = (MyUserDetails) principal;
                Integer userId = userDetails.getUser().getId();

                // 3. 生成 JWT Token
                Map<String, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("exp", DateUtil.currentSeconds());
                String token = JWTUtil.createToken(map, Key.getBytes());

                // 4. 返回响应
                Map<String, Object> resData = new HashMap<>();
                resData.put("token", token);
                resData.put("userId", userId);
                resData.put("userName", user.getUsername()); // 使用请求中的用户名

                System.out.println("认证成功，返回数据: " + resData);

                // 5. 检查 JWT 生成是否成功
                if (token == null || token.isEmpty()) {
                    System.out.println("JWT Token 生成失败");
                    return Result.fail("Token生成失败");
                }

                // 6. 返回完整结果
                Result<Map<String, Object>> result = Result.success(resData);
                System.out.println("最终返回结果: " + result);
                return result;
            } else {
                System.out.println("认证失败：principal 类型错误 - " + principal.getClass().getName());
                return Result.fail("认证失败");
            }
        } catch (BadCredentialsException e) {
            System.out.println("认证失败：密码错误");
            return Result.fail("用户名或密码错误");
        } catch (Exception e) {
            System.out.println("认证失败：" + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息
            return Result.fail("认证过程发生错误");
        }
    }
}